<template>
  <v-app id="inspire">
    <v-content>
      <v-container fluid>
        <v-snackbar
          v-model="snackbar"
        >
          {{ text }}
          <v-btn
            color="pink"
            text
            @click="goToMyContribution"
          >
            {{closeText}}
          </v-btn>
        </v-snackbar>
        <v-card
        >
          <v-card-title>
            <h2 class="display-1">{{meetingName}}</h2>
          </v-card-title>

          <v-card-text>
            <!--会议简介-->
          </v-card-text>

          <v-divider class="mx-4"></v-divider>

          <v-container fluid>
          <v-card-text>
            <span class="subheading">Select Topic</span>
            <v-chip-group
              v-model="topicsSelection"
              :items="meetingTopics"
              active-class="deep-purple--text text--accent-4"
              multiple
              mandatory
            >
              <v-chip v-for="(topic, index) in meetingTopics" :key="index"
              >{{topic.topic}}</v-chip>
            </v-chip-group>
          </v-card-text>

          </v-container>
          <v-container fluid>
          <v-form v-model="valid"
                  ref="form"
          >
            <v-container>
              <v-row>
                <v-col
                  cols="12"
                  md="4"
                >
                  <v-text-field
                    v-model="fileTitle"
                    :rules="titleRule"
                    label="File Title"
                    required
                  ></v-text-field>
                </v-col>
              </v-row>
              <v-row>
                <v-col>
                  <v-combobox
                    v-model="chosenUsers"
                    label="TEAM"
                    multiple
                    outlined
                    chips
                  >
                    <template v-slot:selection="data">
                      <v-chip
                        :key="JSON.stringify(data.item)"
                        v-bind="data.attrs"
                        :input-value="data.selected"
                        :disabled="data.disabled"
                        @click:close="data.parent.selectItem(data.item)"
                      >
                        <v-avatar
                          class="accent white--text"
                          left
                          v-text="data.item.slice(0, 1).toUpperCase()"
                        ></v-avatar>
                        {{ data.item }}
                      </v-chip>
                    </template>
                  </v-combobox>
                </v-col>
              </v-row>

              <v-row>
                <v-col>

                  <span>拖拽确定作者顺序</span>

                  <draggable
                    v-model="chosenUsers"
                    @change="change"
                    @start="start"
                    @end="end"
                    :move="move">
                    <li v-for="(item, index) in chosenUsers" :key="index">
                      第{{index+1}}作者：{{item}}</li>
                  </draggable>
                </v-col>
              </v-row>
                <v-container>
                  <v-row
                    v-for="(author, index) in chosenUsers"
                    :key="author"
                  >
                    <v-col
                      cols="12"
                      md="3"
                    >
                      <v-text-field
                        v-model="chosenUsers[index]"
                        disabled
                        label="Name"
                        required
                      ></v-text-field>
                    </v-col>
                    <v-col
                      cols="12"
                      md="3"
                    >
                      <v-text-field
                        v-model="affiliations[index]"
                        :rules="titleRule"
                        label="Affiliation"
                        required
                      ></v-text-field>

                    </v-col>
                    <v-col
                      cols="12"
                      md="3"
                    >
                    <v-text-field
                      v-model="regions[index]"
                      :rules="titleRule"
                      label="Region"
                      required
                    ></v-text-field>
                    </v-col>
                    <v-col
                      cols="12"
                      md="3"
                    >
                      <v-text-field
                        v-model="emails[index]"
                        :rules="emailRule"
                        label="E-mail"
                        required
                      ></v-text-field>
                    </v-col>
                  </v-row>
                </v-container>
              <v-row>
                <v-col>
                <v-textarea
                  outlined
                  auto-grow
                  name="input-7-4"
                  label="File Abstract"
                  v-model="fileAbstract"
                  :rules="abstractRule"
                ></v-textarea>
                </v-col>
              </v-row>
              <v-row>
                <v-file-input accept=".pdf" label="File input"></v-file-input>
              </v-row>
              <v-row>
                <v-col>
                <v-btn
                  color="blue-grey"
                  class="ma-2 white--text"
                  @click="submit"
                >
                  Upload
                  <v-icon right dark>mdi-cloud-upload</v-icon>
                </v-btn>
                <v-btn
                  color="blue-grey"
                  class="ma-2 white--text"
                  @click="uploadFile"
                >
                  Preview
                </v-btn>
                </v-col>
              </v-row>
              <div class="canvas-container">
                <canvas ref="myCanvas" class="pdf-container col-md-10 ml-auto mr-auto">
                </canvas>
              </div>
            </v-container>
          </v-form>
          </v-container>
        </v-card>
<side-bar></side-bar>
      </v-container>
    </v-content>
  </v-app>
</template>

<script>
  import SideBar from './Components/SideBar'
import draggable from 'vuedraggable'
import pdfJS from 'pdfjs-dist'
import axios from 'axios'
import store from '../store'

export default {
  computed: {
    draggingInfo () {
      return this.dragging ? 'under drag' : ''
    }
  },
  data () {
    const generateTopic = _ => {
      const data = []
      this.$axios.post('/getMeetingTopics', this.$route.params.id)
        .then(resp => {
          if (resp != null) {
            var response = resp.data
            response.forEach((topic, index) => {
              data.push({
                topic: topic
              })
            })
          }
        })
        .catch(error => {
          console.log(error)
          // alert('get topics error')
        })
      return data
    }
    return {
      titleRule: [
        v => !!v || 'Required'
      ],
      emailRule: [
        v => !!v || 'E-mail is required',
        v => /.+@.+/.test(v) || 'E-mail must be valid'
      ],
      abstractRule: [
        v => !!v || 'Abstract Required',
        v => v.length <= 100 || 'Must be less than 100 characters'
      ],

      meetingName: this.$route.params.id,
      pdfData: '', // PDF的base64
      scale: 2, // 缩放值
      select: null,
      valid: '',
      fileTitle: '',
      snackbar: false,
      text: '',
      closeText: 'Close',
      fileAbstract: '',
      meetingTopics: generateTopic(),
      chosenUsers: [
        'wuyanjie',
        'taozixin',
        'yuzhexuan'
      ],
      topicsSelection: [],
      // chosenTopics: [],
      authors: [
        'taozixin',
        'yuzhexuan'
      ],
      affiliations: [],
      regions: [],
      emails: [],
      dragging: false
    }
  },
  methods: {
    openApplyPage: function () {
      this.$router.replace({path: '/applyMeeting'})
    },
    submit: function () {
      if (this.$refs.form.validate()) {
        if (this.topicsSelection.length === 0) {
          this.text = '未选择topic'
          this.snackbar = true
        } else if (this.chosenUsers.length === 0) {
          this.text = '未选择author'
          this.snackbar = true
        } else if (document.querySelector('input[type=file]').files.length === 0) {
          this.text = '请选择文件!'
          this.snackbar = true
        } else {
          // var formData = new FormData() // 声明一个FormData对象
          var formData = new window.FormData() // vue 中使用 window.FormData(),否则会报 'FormData isn't definded'

          var data = []
          // var chosen = this.chosenTopics
          var all = this.meetingTopics
          this.topicsSelection.forEach((topicIndex, index) => {
            data[index] = all[topicIndex].topic
          })
          formData.set('file', document.querySelector('input[type=file]').files[0]) // 'file' 这个名字要和后台获取文件的名字一样;
          formData.set('user', store.state.userName)
          formData.set('meeting', this.meetingName)
          formData.set('newFileTitle', this.fileTitle)
          formData.set('originalFileTitle', null)
          formData.set('fileAbstract', this.fileAbstract)
          formData.set('topics', data)
          formData.set('authorNames', this.chosenUsers)
          formData.set('authorAffiliations', this.affiliations)
          formData.set('authorRegions', this.regions)
          formData.set('authorEmails', this.emails)

          // console.log(formData)

          axios({
            url: '/uploadWork',
            data: formData,
            method: 'post',
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then((res) => {
            if (res.status === 200) {
              console.log(res.data)
              this.text = 'success'
              this.closeText = 'OKAY'
              this.snackbar = true
            } else {
              this.text = 'fail to upload'
              this.snackbar = true
            }
            // alert('Success')
            // location.reload()
          })
            .catch(error => {
              console.log(error)
              this.text = 'upload error'
              this.snackbar = true
              // alert('Fail to upload')
            })
        }
      }
    },
    goToMyContribution () {
      this.snackbar = false
      if (this.closeText === 'OKAY') {
        this.$router.push('/myContribution')
      }
    },
    uploadFile () {
      let file = document.querySelector('input[type=file]').files[0]
      // console.log(file.name)
      let reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        this.pdfData = atob(reader.result.substring(reader.result.indexOf(',') + 1))
        this.previewPDF()
      }
    },
    previewPDF () {
      // 引入pdf.js的字体
      let CMAP_URL = 'https://unpkg.com/pdfjs-dist@2.0.943/cmaps/'
      // 读取base64的pdf流文件
      let loadingTask = pdfJS.getDocument({
        data: this.pdfData, // PDF base64编码
        cMapUrl: CMAP_URL,
        cMapPacked: true
      })
      loadingTask.promise.then((pdf) => {
        this.loadFinished = true
        let numPages = pdf.numPages
        let pageNumber = 1
        this.getPage(pdf, pageNumber, numPages)
      })
    },
    getPage (pdf, pageNumber, numPages) {
      let _this = this
      pdf.getPage(pageNumber)
        .then((page) => {
          // 获取DOM中为预览PDF准备好的canvasDOM对象
          let canvas = this.$refs.myCanvas
          let viewport = page.getViewport(_this.scale)
          canvas.height = viewport.height
          canvas.width = viewport.width

          let ctx = canvas.getContext('2d')
          let renderContext = {
            canvasContext: ctx,
            viewport: viewport
          }
          page.render(renderContext)
            .then(() => {
              pageNumber += 1
              if (pageNumber <= 1) {
                _this.getPage(pdf, pageNumber, numPages)
              }
            })
        })
    },

    change (evt) {
      console.log(evt)
    },
    // start ,end ,add,update, sort, remove 得到的都差不多
    start (evt) {
      console.log(evt)
    },
    end (evt) {
      // console.log(evt)
      // evt.item // 可以知道拖动的本身
      // evt.to // 可以知道拖动的目标列表
      // evt.from // 可以知道之前的列表
      // evt.oldIndex // 可以知道拖动前的位置
      // evt.newIndex // 可以知道拖动后的位置
    },
    move (evt, originalEvent) {
      console.log(evt)
      console.log(originalEvent) // 鼠标位置
    },

    removeAt (idx) {
      this.list.splice(idx, 1)
    },
    add: function () {
      id++
      this.list.push({ name: 'Juan ' + id, id, text: '' })
    }
  },
  components: {
    SideBar,
    draggable
  }
}
</script>

<style scoped>
  .button {
    margin-top: 35px;
  }
  .handle {
    float: left;
    padding-top: 8px;
    padding-bottom: 8px;
  }
  .close {
    float: right;
    padding-top: 8px;
    padding-bottom: 8px;
  }
  input {
    display: inline-block;
    width: 50%;
  }
  .text {
    margin: 20px;
  }
</style>
